package com.bjpowernode.boss.common.exception.handle;

import com.bjpowernode.boss.common.enums.ResponseCode;
import com.bjpowernode.boss.common.exception.BossException;
import com.bjpowernode.boss.mvc.models.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author Mrs.cui
 * 2024-07-08-17-13
 */
@RestControllerAdvice
public class GlobalExceptionHandle {
    Logger logger = LoggerFactory.getLogger(getClass());

    //处理BossException
    @ExceptionHandler({BossException.class})
    public AjaxResult doBossException(BossException bossException){
        ResponseCode responseCode = bossException.getResponseCode();
        logger.error("发生了BossException异常，code:{},mag:{}",responseCode.getNumber(),responseCode.getMsg());

        AjaxResult ajaxResult = AjaxResult.fail(responseCode);
        return ajaxResult;
    }

    //处理Bean Vaildation异常
    @ExceptionHandler(BindException.class)
    public AjaxResult doBeanValidation(BindException bindException) {
        BindingResult bindingResult = bindException.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        StringBuilder builder = new StringBuilder();
        fieldErrors.forEach(fl -> {
           /* builder.append("错误项：【").append(fl.getField()).append("】，原因：【")
                             .append(fl.getDefaultMessage()).append("】");*/
            builder.append("【")
                    .append(fl.getDefaultMessage()).append("】; ");
        });

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setCode(ResponseCode.REQUEST_PARAM_ERR.getNumber());
        ajaxResult.setMsg(ResponseCode.REQUEST_PARAM_ERR.getMsg() + "|原因：" + builder.toString());
        ajaxResult.setData("");
        return ajaxResult;
    }
}
